package com.wh.wisdomsite.xbox.server.listener;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wh.wisdomsite.xbox.al.entity.AlarmSign;
import com.wh.wisdomsite.xbox.al.entity.UserAlarm;
import com.wh.wisdomsite.xbox.al.service.IAlarmSignService;
import com.wh.wisdomsite.xbox.al.service.IUserAlarmService;
import com.wh.wisdomsite.xbox.us.entity.User;
import com.wh.wisdomsite.xbox.us.service.IUserService;
import io.goeasy.GoEasy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPubSub;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * redis订阅监听器
 *
 * @version V1.0
 * @Package: com.wh.wisdomsite.xbox.server.listener
 * @author: 丁奕
 * @date: 2018-09-25 10:40
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 **/
@Component
public class RedisMsgPubSubListener extends JedisPubSub {

    private static final Log logger = LogFactory.getLog(RedisMsgPubSubListener.class);

    public static RedisMsgPubSubListener redisMsgPubSubListener;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @PostConstruct
    public void init() {
        redisMsgPubSubListener = this;
    }

    @Autowired
    IAlarmSignService iAlarmSignService;

    @Autowired
    IUserService iUserService;

    @Autowired
    IUserAlarmService iUserAlarmService;

    @Override
    public void unsubscribe() {
        super.unsubscribe();
    }

    @Override
    public void unsubscribe(String... channels) {
        super.unsubscribe(channels);
    }

    @Override
    public void subscribe(String... channels) {
        super.subscribe(channels);
    }

    @Override
    public void psubscribe(String... patterns) {
        super.psubscribe(patterns);
    }

    @Override
    public void punsubscribe() {
        super.punsubscribe();
    }

    @Override
    public void punsubscribe(String... patterns) {
        super.punsubscribe(patterns);
    }

    @Override
    public void onMessage(String channel, String message) {
        logger.debug("redis订阅者获取到消息，channel:" + channel + "receives message :" + message);
        try {
            JSONObject json = new JSONObject(message);
            String deviceId = json.getString("device_id");
            //先判断此次报警的事件是否已经进行过存储，没有存储再进行存储操作
            EntityWrapper<AlarmSign> ew = new EntityWrapper<>();
            ew.setEntity(new AlarmSign());
            ew.eq("recordId",json.getString("events_id"));
            List<AlarmSign> alarmSignList = redisMsgPubSubListener.iAlarmSignService.selectList(ew);
            if(alarmSignList == null || alarmSignList.isEmpty()){
                List<String> projectIds = redisMsgPubSubListener.iAlarmSignService.getProjectIdByDeviceId(deviceId);
                for (String projectId : projectIds){
                    AlarmSign alarmSign = new AlarmSign();
                    alarmSign.setAlId(UUID.randomUUID().toString().replace("-",""));
                    alarmSign.setPrId(projectId);
                    alarmSign.setAlarmTime(sdf.parse(json.getString("created_at")));
                    alarmSign.setAlarmType("1");
                    //设置警报类别，扬尘或是起重机械
                    String alarmCategory = "1";
                    if(json.getString("alarm_type").indexOf("ENV") > -1){
                        alarmCategory = "2";
                    }
                    alarmSign.setAlarmCategory(alarmCategory);
                    //设置警报细分
                    alarmSign.setAlarmSubdivided(json.getString("alarm_type"));
                    alarmSign.setDeviceName(json.getString("device_name"));
                    alarmSign.setDeviceId(json.getString("device_id"));
                    alarmSign.setAlarmData(json.getString("value"));
                    alarmSign.setAlarmContent(json.getString("alarm_name"));
                    alarmSign.setRecordId(json.getString("events_id"));
                    alarmSign.setCreateBy("1");
                    alarmSign.setCreateDate(new Date());
                    redisMsgPubSubListener.iAlarmSignService.insert(alarmSign);
                    //使用GOEASY推送有新警报信息
                    GoEasy goEasy = new GoEasy("BC-f9e55149bfec44d0b672e377bee262e4");
                    goEasy.publish("alarmChannel", "new Alarm");
                    //查询有此项目查询权限的所有user
                    List<User> users = redisMsgPubSubListener.iUserService.selectUserListByProjectId(projectId);
                    //生成对应的用户警报，并存储
                    for (User user : users){
                        UserAlarm userAlarm = new UserAlarm();
                        userAlarm.setUaId(UUID.randomUUID().toString().replace("-",""));
                        userAlarm.setAlId(alarmSign.getAlId());
                        userAlarm.setUsId(user.getUsId());
                        userAlarm.setCheckStatus("1");
                        //使用GOEASY进行推送
                        StringBuffer contentSb = new StringBuffer();
                        contentSb.append("亲爱的管理员：" + user.getLoginName() + ",您有一条新的报警信息！\n</br>");
                        contentSb.append("<a href='javascript:void(0);' onclick='openAlarmList("+alarmCategory+")'>点击查看</a>");
                        goEasy.publish("userAlarmChannel:"+user.getUsId(), contentSb.toString());
                        userAlarm.setPushStatus("2");
                        redisMsgPubSubListener.iUserAlarmService.insert(userAlarm);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onPMessage(String pattern, String channel, String message) {

    }

    @Override
    public void onSubscribe(String channel, int subscribedChannels) {
        System.out.println("channel:" + channel + "is been subscribed:" + subscribedChannels);
    }

    @Override
    public void onPUnsubscribe(String pattern, int subscribedChannels) {

    }

    @Override
    public void onPSubscribe(String pattern, int subscribedChannels) {

    }

    @Override
    public void onUnsubscribe(String channel, int subscribedChannels) {
        System.out.println("channel:" + channel + "is been unsubscribed:" + subscribedChannels);
    }

}
